﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FAP.GetComment.DTO;
using HtmlAgilityPack;
using FAP.DataAccess.BLL;
using FAP.DataAccess;
using log4net;

namespace FAP.GetComment.GUI
{
    public partial class ucGetComment : UserControl
    {
        List<News> lstNews;
        List<string> links = new List<string>();
        List<baiviet> _baiviets = new List<baiviet>();
        private ILog m_log = LogManager.GetLogger(typeof(ucGetComment));
        private List<XPath> GetXPath()
        {
            List<XPath> xPaths = new List<XPath>();
            XPath xpath = new XPath();

            xpath.Id = 0;
            xpath.Domain = "Choose";
            xPaths.Add(xpath);

            xpath = new XPath();
            xpath.Id = 1;
            xpath.Domain = "http://forum.zing.vn/";
            xpath.Url = "http://forum.zing.vn/fanfiction/12-chom-sao-noi-ay-anh-co-gap-lai-em/t1308530.html";
            xpath.Root = "//*[@id=\"postlist\"]/ol/li";
            xpath.Date = "div[1]/div[1]/span[1]";
            xpath.Authors = "div[1]/div[2]/div[1]/div[1]/div[1]/a[1]/strong[1]";
            xpath.Title = "div[2]/div[1]/h2[1]";
            xpath.Content = "div[2]/div[1]/div[1]/div[1]/blockquote[1]";
            xPaths.Add(xpath);

            xpath = new XPath();
            xpath.Id = 2;
            xpath.Domain = "http://fap.tonghophoanhao.com";
            xpath.Root = "//*[@id=\"postlist\"]/ol/li";
            xpath.Date = "div[1]/span[1]/span[1]";
            xpath.Url = "http://fap.tonghophoanhao.com/showthread.php?9-Bai-post-1";
            xpath.Authors = "div[2]/div[1]/div[1]/div[1]/a[1]/strong[1]";
            xpath.Title = "div[2]/div[2]/div[1]/h2[1]";
            xpath.Content = "div[2]/div[2]/div[1]/div[1]/div[1]/blockquote[1]";
            xPaths.Add(xpath);

            xpath = new XPath();
            xpath.Id = 3;
            xpath.Domain = "http://www.webtretho.com/";
            xpath.Root = "//*[@id=\"postlist\"]/ol/li";
            xpath.Date = "div[1]/span[1]/span[1]";
            xpath.Url = "http://www.webtretho.com/forum/f187/hay-viet-nhung-gi-ban-dang-nghi-tang-3-a-1759850/";
            xpath.Authors = "div[1]/div[2]/div[1]/div[1]/div[1]/a[1]/strong[1]";
            xpath.Title = "div[2]/div[1]/h2[1]";
            xpath.Content = "div[2]/div[1]/div[1]/div[1]/blockquote[1]";
            xPaths.Add(xpath);

            xpath = new XPath();
            xpath.Id = 4;
            xpath.Domain = "http://www.vn-zoom.com";
            xpath.Root = "//*[@id=\"postlist\"]/div/ol/li";
            xpath.Date = "div[1]/div[1]/span[1]/span[1]";
            xpath.Url = "http://www.vn-zoom.com/f2/thong-bao-ve-trang-download-cua-vn-zoom-2407358.html";
            xpath.Authors = "div[1]/div[2]/div[1]/div[1]/div[1]/a[1]/strong[1]";
            xpath.Title = "div[2]/div[1]/h2[1]";
            xpath.Content = "div[2]/div[1]/div[1]/div[1]/blockquote[1]";
            xPaths.Add(xpath);

            xpath = new XPath();
            xpath.Id = 5;
            xpath.Domain = "http://www.diendan.eva.vn";
            xpath.Root = "//*[@id=\"posts\"]/div";
            xpath.Date = "div/div/div/table[1]/tr[1]/td[1]/div[2]";
            xpath.Url = "http://www.diendan.eva.vn/huong-dan-mua-va-ban-hang-trong-sieu-thi-ishop-t75939.html";
            xpath.Authors = "div/div/div/table[1]/tr[2]/td[1]/table[1]/tr[1]/td[2]/div[1]/a[1]/font[1]/b[1]";
            xpath.Title = "div/div/div/table[1]/tr[3]/td[1]/div[1]/strong[1]";
            xpath.Content = "div/div/div/table[1]/tr[3]/td[1]/div[2]";
            xPaths.Add(xpath);

            xpath = new XPath();
            xpath.Id = 6;
            xpath.Domain = "http://raovat.123mua.vn/";
            xpath.Root = "//*[@id=\"content\"]/div[2]";
            xpath.Date = "div[3]/div[2]/div[1]/p[1]/span[2]";
            xpath.Url = "http://raovat.123mua.vn/TP-HCM/Du-hoc-thuy-sy-chuong-trinh-vua-hoc-vua-lam-323089.html";
            xpath.Authors = "div[3]/div[2]/div[2]/span[2]/span[2]/a[1]";
            xpath.Title = "div[3]/div[1]/h1[1]";
            xpath.Content = "div[3]/div[5]";
            xPaths.Add(xpath);

            return xPaths;
        }
        private void LoadDataComment()
        {
            int iCount = lstNews.Count;
            lvNews.Items.Clear();
            //lstNews = lstNews.OrderBy(m => m.Authors).ToList();
            pb_TaskProccess.Minimum = 0;
            pb_TaskProccess.Maximum = lstNews.Count;
            pb_TaskProccess.Value = 0;
            pb_TaskProccess.Step = 1;
            int i = 1;
            foreach (var item in lstNews)
            {

                ListViewItem lvi = new ListViewItem();
                lvi.Text = item.Authors;
                lvi.SubItems.Add(item.Url);
                lvi.SubItems.Add(item.Title);
                lvi.SubItems.Add(item.Content);
                lvi.SubItems.Add(item.Date);
                lvi.Tag = item;
                lvNews.Items.Add(lvi);
                pb_TaskProccess.PerformStep();
                m_log.Info("Item " + i + " loaded");//uh nhu vay ne
                i++;
                lblProcess.Text = pb_TaskProccess.Value + "/" + iCount;
            }
        }

        private void LoadBaiViet(List<baiviet> baiviets)
        {
            //Cách ghi log:

            //cư the ma lam
            //List<baiviet> baiviets = new List<baiviet>();
            //baiviets = FAP.DataAccess.BLL.baiviet.baivietSelectRowByForeignKey_websiteId(websiteId);
            int iCount = baiviets.Count;
            lvBaiViet.Items.Clear();

            pb_TaskProccess.Minimum = 0;
            pb_TaskProccess.Maximum = baiviets.Count;
            pb_TaskProccess.Value = 0;
            pb_TaskProccess.Step = 1;

            for (int i = 0; i < iCount; i++)
            {

                ListViewItem lvi = new ListViewItem();
                lvi.Text = (i + 1).ToString();
                lvi.SubItems.Add(baiviets[i].link);
                lvi.SubItems.Add(baiviets[i].ngaytao.ToString());
                lvi.Tag = baiviets[i];
                lvBaiViet.Items.Add(lvi);
                m_log.Info("Item " + (i + 1) + " loaded");//uh nhu vay ne
                pb_TaskProccess.PerformStep();
                lblProcess.Text = pb_TaskProccess.Value + "/" + iCount;
            }


        }


        public void GetCommentByWebsiteVB(XPath xpath)
        {
            m_log.Info("CLGT");
            var site = new HtmlWeb();
            var doc = site.Load(xpath.Url);
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(xpath.Root);
            if (nodes != null)
            {
                News model;

                foreach (var item in nodes)
                {

                    model = new News();
                    model.Url = xpath.Url;
                    var tempAuthors = item.SelectNodes(xpath.Authors);
                    if (tempAuthors != null && tempAuthors.Count > 0)
                    {
                        model.Authors = tempAuthors[0].InnerText.Trim();
                    }

                    var tempDate = item.SelectNodes(xpath.Date);
                    if (tempDate != null && tempDate.Count > 0)
                    {
                        model.Date = tempDate[0].InnerText.Trim();
                    }

                    var tempTitle = item.SelectNodes(xpath.Title);
                    if (tempTitle != null && tempTitle.Count > 0)
                    {
                        model.Title = tempTitle[0].InnerText.Trim();
                    }
                    var tempContent = item.SelectNodes(xpath.Content);
                    if (tempContent != null && tempContent.Count > 0)
                    {
                        model.Content = tempContent[0].InnerText.Trim();
                    }
                    if (tempAuthors == null && tempContent == null)
                    {
                        continue;
                    }
                    model.IdBaiViet = xpath.IdBaiViet;
                    m_log.Info("Content loadding " + model.Content + "...");//uh nhu vay ne
                    lstNews.Add(model);
                }

            }
        }

        public List<website> GetListWebsite()
        {
            List<website> websites = new List<website>();
            websites = WebsiteDAO.GetWebSite().OrderBy(m => m.link).ToList();
            return websites;
        }

        private List<baiviet> GetBaiVietSelected()
        {
            List<baiviet> baiviets = new List<baiviet>();
            var items = lvBaiViet.CheckedIndices;
            foreach (var item in items)
            {
                int ind = int.Parse(item.ToString());
                var baiviet = (baiviet)lvBaiViet.Items[ind].Tag;
                baiviets.Add(baiviet);
            }
            return baiviets;
        }

        public ucGetComment()
        {
            InitializeComponent();
            //cmbForum.DataSource = GetXPath();
            //cmbForum.DisplayMember = "Domain";
            //cmbForum.ValueMember = "Id";
            List<website> websites = GetListWebsite();
            cmbForum.DataSource = websites;
            cmbForum.DisplayMember = "link";
            cmbForum.ValueMember = "id";
        }

        private void btnGetComment_Click(object sender, EventArgs e)
        {
            lblProcess.Text = "0%";
            XPath xpath = new XPath();
            int index = cmbForum.SelectedIndex;

            xpath.Url = txtUrl.Text;
            xpath.Root = txtXPathRoot.Text.ToString();
            xpath.Title = txtXPathTitle.Text.ToString();
            xpath.Authors = txtXPathAuthors.Text.ToString();
            xpath.Content = txtXPathContent.Text.ToString();
            xpath.Date = txtXPathDate.Text.ToString();
            if (string.IsNullOrEmpty(xpath.Root)
                || string.IsNullOrEmpty(xpath.Authors)
                || string.IsNullOrEmpty(xpath.Title)
                || string.IsNullOrEmpty(xpath.Content))
            {
                MessageBox.Show("The field [XPath ] is required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            xpath.Date = txtXPathDate.Text;
            lstNews = new List<News>();

            #region Lay danh sach link bai viet

            List<baiviet> baiviets = GetBaiVietSelected();
            if (baiviets == null || baiviets.Count == 0)
            {
                if (string.IsNullOrEmpty(xpath.Url))
                {
                    MessageBox.Show("Please enter [Forum Url] or select [List Link] get feedback!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    xpath.Url = txtUrl.Text;
                    GetCommentByWebsiteVB(xpath);
                }
            }
            else
            {
                foreach (var item in baiviets)
                {

                    xpath.Url = item.link;
                    xpath.IdBaiViet = item.id;
                    GetCommentByWebsiteVB(xpath);
                }
            }
            #endregion
            LoadDataComment();
        }

        private void cmbForum_SelectedIndexChanged(object sender, EventArgs e)
        {
            pb_TaskProccess.Value = 0;
            lblProcess.Text = pb_TaskProccess.Value + "/0";
            lvNews.Items.Clear();
            website website = (website)cmbForum.SelectedItem;
            xpath xpath = new xpath();
            xpath = (xpath)FAP.DataAccess.BLL.xpath.xpathSelectRowByForeignKey_websiteid(website.id).FirstOrDefault();
            if (xpath != null)
            {
                txtXPathRoot.Text = xpath.root;
                txtXPathTitle.Text = xpath.title;
                txtXPathAuthors.Text = xpath.authors;
                txtXPathContent.Text = xpath.content;
                txtXPathDate.Text = xpath.date;
            }
            else
            {
                txtXPathRoot.Text = "";
                txtXPathTitle.Text = "";
                txtXPathAuthors.Text = "";
                txtXPathContent.Text = "";
                txtXPathDate.Text = "";
            }
            _baiviets = FAP.DataAccess.BLL.baiviet.baivietSelectRowByForeignKey_websiteId(website.id);
            LoadBaiViet(_baiviets);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {

        }

        private void btnSaveComment_Click(object sender, EventArgs e)
        {

            if (lstNews == null || lstNews.Count == 0)
            {
                MessageBox.Show("List comment is null", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
            foreach (var item in lstNews)
            {
                m_log.Info("Item " + item.Url + " saved");//uh nhu vay ne
                FAP.DataAccess.BLL.comment.commentInsertRow(0, item.IdBaiViet, item.Url, item.Authors, item.Title, item.Content, DateTime.Now, false);

            }
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            DateTime fromDate = new DateTime();
            DateTime toDate = new DateTime();
            fromDate = DateTime.Parse(dtpFromDate.Text);
            toDate = DateTime.Parse(dtpToDate.Text);
            List<baiviet> temp = _baiviets.Where(m => m.ngaytao >= fromDate && m.ngaytao <= toDate).ToList();
            LoadBaiViet(temp);
        }

        //private void dtpFromDate_ValueChanged(object sender, EventArgs e)
        //{
        //    DateTime fromDate = new DateTime();
        //    DateTime toDate = new DateTime();
        //    fromDate = DateTime.Parse(dtpFromDate.Text);
        //    toDate = DateTime.Parse(dtpToDate.Text);
        //    List<baiviet> temp = _baiviets.Where(m => m.ngaytao >= fromDate  && m.ngaytao<= toDate).ToList();
        //    LoadBaiViet(temp);
        //}

        //private void dtpToDate_ValueChanged(object sender, EventArgs e)
        //{
        //    DateTime fromDate = new DateTime();
        //    DateTime toDate = new DateTime();
        //    fromDate = DateTime.Parse(dtpFromDate.Text);
        //    toDate = DateTime.Parse(dtpToDate.Text);
        //    List<baiviet> temp = _baiviets.Where(m => m.ngaytao >= fromDate && m.ngaytao <= toDate).ToList();
        //    LoadBaiViet(temp);

        //}


    }
}
